package cn.wzptsoft.mall.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.wzptsoft.mall.mapper.OrderItemMapper;
import cn.wzptsoft.mall.mapper.SkuMapper;
import cn.wzptsoft.mall.pojo.OrderItem;
import cn.wzptsoft.mall.pojo.Sku;
import cn.wzptsoft.mall.pojo.dto.PutOrderDTO;
import cn.wzptsoft.mall.pojo.vo.OrderInfoVO;
import cn.wzptsoft.mall.service.IOrderItemService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IOrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements IOrderItemService {

    @Autowired
    private SkuMapper skuMapper;

    @Override
    public void add(Long orderId, List<PutOrderDTO.SpuInfoDTO> spuInfo) {
        List<OrderItem> list=new ArrayList<>();

        spuInfo.forEach(item->{
            LambdaQueryWrapper<Sku> wrapper=new LambdaQueryWrapper<>();
            wrapper.eq(Sku::getId,item.getSkuId());
            Sku sku = skuMapper.selectOne(wrapper);
           if (sku.getPrice().compareTo(item.getSkuPrice())!=0){
               throw new RuntimeException("价格异常");
           }

            list.add(OrderItem.builder()
                    .orderId(orderId)
                    .spuId(item.getSpuId())
                    .count(item.getCount())
                    .skuId(item.getSkuId())
                    .snapTitle(item.getSkuTitle())
                    .snapPrice(item.getSkuPrice())
                    .build()
            );
        });

        saveBatch(list);

    }

    @Override
    public Map<Integer, List<OrderInfoVO.OrderInfoVoItem>> getOrderInfoVoItemByIds(List<Integer> list) {
        Map<Integer, List<OrderInfoVO.OrderInfoVoItem>> res = new HashMap<>();
        list.forEach(i->{
            //查询每条id的orderitem
            List<OrderItem> orderItems = lambdaQuery().eq(OrderItem::getOrderId, i)
                    //将查询到的数据转换成OrderInfoVoItem
                    .list();

            List<OrderInfoVO.OrderInfoVoItem> orderInfoVoItems =  orderItems .stream().map(j -> BeanUtil.copyProperties(j, OrderInfoVO.OrderInfoVoItem.class))
                    .toList();
            res.put(i,orderInfoVoItems);
        });
        return res;
    }
}
